from netMessages import NetMessages
from dbHelper import DbHelper

NET_MESSAGES = NetMessages()
db = DbHelper()

class NetMsgService:
    def __init__(self) -> None:
        pass


    async def userLeaveRoom(self, user, gameServer):
        if user.room == None:
            return True
    
        room = user.room
        roomWasGaming = room.isGaming()
        userWasGaming = user.isGaming()
        room.userLeave(user)
        roomNowGaming = room.isGaming()

        if user.isRoomMaster == True and room.getUserCount() > 0:
            nextUser = room.getUsers()[0]
            nextUser.isRoomMaster = True

        remainUserCount = room.getUserCount()
        if remainUserCount <= 0:
            gameServer.destroyRoom(room)

            messageRoomDestroyed = {}
            await gameServer.broadcastMessage(NET_MESSAGES.NM_ROOM_DESTROYED, messageRoomDestroyed)
        else:
            messageUserLeft = {
                "user": user.toDTO(),
                "room" : room.toDTO()
            }
            await gameServer.broadcastMessageRoomExcept(NET_MESSAGES.NM_LEAVEROOM_RESULT, messageUserLeft, room, user.getClientSocket())

        if userWasGaming:
            userGameEndNotifyData = {
                "user": user.toDTO()
            }
            
            await gameServer.broadcastMessageRoom(NET_MESSAGES.NM_USER_GAME_END_NOTIFY, userGameEndNotifyData, room)

        if roomWasGaming and not roomNowGaming:
            await gameServer.broadcastMessageRoom(NET_MESSAGES.NM_GAME_END, {}, room)


    async def userReady(self, user, gameServer):
        if user.getRoom() == None:
            return
            
        user.setReady()
        await gameServer.broadcastMessageRoom(NET_MESSAGES.NM_ROOM_CHANGED, {}, user.getRoom())


    async def userCancelReady(self, user, gameServer):
        if user.getRoom() == None:
            return
            
        user.cancelReady()
        await gameServer.broadcastMessageRoom(NET_MESSAGES.NM_ROOM_CHANGED, {}, user.getRoom())


    async def gameStart(self, user, gameServer):
        if user.getRoom() == None:
            return
        
        room = user.getRoom()
        room.gameStart()
            
        await gameServer.broadcastMessageRoom(NET_MESSAGES.NM_GAME_START, {}, room)

    
    async def uploadScore(self, user, score, gameServer):
        localData = db.getData()
        
        if user.userName in localData:
            if score > localData[user.userName]:
                localData[user.userName] = score
        else:
            localData[user.userName] = score

        db.storeData(localData)

        response = {
            "result": True
        }
        await gameServer.sendMessage(NET_MESSAGES.NM_UPLOAD_SCORE_RESULT, response, user.getClientSocket())


    def getScoreInfo(self):
        return db.getData()